package com.tomato.limit.standalone;

import com.tomato.limit.standalone.param.LimitParam;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 计数器算法
 * TODO
 * @author lizhifu
 * @date 2022/3/4
 */
public class CounterAlgorithm {
    /**
     * 当前计数器
     */
    private ConcurrentHashMap<String,AtomicInteger> limitMap = new ConcurrentHashMap();
    /**
     * 请求时间
     */
    private long time;

    public boolean limit(LimitParam limitParam) {
        AtomicInteger reqCount = limitMap.putIfAbsent(limitParam.getKey(),new AtomicInteger(0));
        long now = System.currentTimeMillis();
        if (now < time + limitParam.getTimeout()) {
            // 单位时间内
            reqCount.addAndGet(1);
            return reqCount.get() <= limitParam.getLimit();
        } else {
            // 超出单位时间
            time = now;
            reqCount = new AtomicInteger(0);
            return true;
        }
    }
}
